﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RWLib
{
    class SometimesConditionQuery : Query
    {

        private Formula condition;
        private int time;

        public SometimesConditionQuery(Tree _tree, Formula _cond, int _time)
        {
            condition = _cond;
            tree = _tree;
            time = _time;
        }

        public Formula Condition {
            get { return condition; }
            set { condition = value; }
        }

        override public bool Run() {
            List<Node> children = tree.Root.Nodes;
            List<Node> nodes = children;
            int currTime = -1;
            bool result = false;
            while (children.Count > 0 && currTime != time)
            {
                currTime = children.First().t;
                nodes = children;
                children = children.Select(c => c.Nodes).SelectMany(c => c).ToList();
            }
            if (currTime == -1)
            {
                result = false;
            }
            else
            {
                result = nodes.Any(c => condition.Eval(c.Fluents));
            }
            return result;
        }    
    }
}